import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Spin, message } from 'antd';
import { serialize } from '../../../common/tool';
import fetchJsonp from 'fetch-jsonp';
import { ConfigContext } from '../config-provider';

function getUploadDownloadInfo(key, path) {
    let pathUrl = path;
    if (key) {
        pathUrl += (/\?/.test(path) ? '&' : '?') + serialize({ key });
    }
    return fetchJsonp(pathUrl, {
        jsonpCallback: 'jsonpCallback',
    }).then((response) => response.json());
}

class RmsFilesDown extends Component {
    constructor(props) {
        super(props);
        this.state = {
            redirectUrl: '',
            loading: true,
        };
        this.open = true;
        this.handleFetchDownUrl = this.handleFetchDownUrl.bind(this);
    }

    componentDidUpdate(preProps) {
        const { url } = this.props;
        if (url !== preProps.url) {
            this.handleFetchDownUrl();
        }
    }

    componentDidMount() {
        this.handleFetchDownUrl();
    }

    componentWillUnmount() {
        this.open = false;
    }

    render() {
        const { redirectUrl, loading } = this.state;
        const { content, showTip } = this.props;
        return (
            <Spin spinning={loading} tip={showTip || ''}>
                {redirectUrl ? (
                    <a href={redirectUrl} target="__blank" download>
                        {content}
                    </a>
                ) : null}
            </Spin>
        );
    }

    handleFetchDownUrl() {
        const { url, filename } = this.props;
        const { uploadTokenURI } = this.context;
        const apiPath = `${uploadTokenURI}/getDownloadParamJsonp`;
        if (!url.match(/\?key=(.+)/)) {
            this.setState({
                loading: false,
                redirectUrl: url,
            });
            return;
        }
        const decodeUrl = decodeURIComponent(url.match(/\?key=(.+)/)[1]);
        getUploadDownloadInfo(decodeUrl, apiPath)
            .then((data) => {
                const file = data.data;
                const fileType = file.mimetype.split('/')[1];
                const downName = /\..+/.test(filename) ? filename : `${filename}.${fileType}`; // 如果传入的filename已经包含后缀名
                if (this.open) {
                    this.setState({
                        loading: false,
                        redirectUrl:
              file.mimetype.split('/')[0] === 'image'
                  ? `${file.downloadUrl}?attname=${encodeURIComponent(downName)}`
                  : file.downloadUrl,
                    });
                }
            })
            .catch((err) => {
                this.setState({
                    loading: false,
                });
                message.error(`获取下载地址失败:${err.message}`);
            });
    }
}

RmsFilesDown.contextType = ConfigContext;

RmsFilesDown.propTypes = {
    url: PropTypes.string.isRequired, // 文件地址
    content: PropTypes.object.isRequired,
    filename: PropTypes.string.isRequired,
    showTip: PropTypes.string,
};

export default RmsFilesDown;
